package com.skyline.common.util;

import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skyline.common.exception.BusinessException;

/**
 * 页面以及Controller使用的帮助类，用户session处理，获取request等操作
 * 
 * @author wuqh
 * 
 */
public class WebHelper {

	/**
	 * 根据传入的request情况获取实际的request，如果不为空则不做任何改变 如果传入request为空则获取当前线程中设置的request
	 * 
	 * @param request 传入的HttpServletResponse 可以为空
	 * @return
	 */
	public static HttpServletRequest initRequest(HttpServletRequest request) {
		if (request == null) {
			request = RequestContainer.getRequest();
		}
		if (request == null) {
			throw new BusinessException("传入的request为空，而且当前线程中也不存在HttpServletRequest对象");
		}
		return request;
	}

	/**
	 * 根据传入的response情况获取实际的response，如果不为空则不做任何改变
	 * 如果传入response为空则获取当前线程中设置的response
	 * 
	 * @param response
	 *            传入的HttpServletResponse 可以为空
	 * @return
	 */
	public static HttpServletResponse initResponse(HttpServletResponse response) {
		if (response == null) {
			response = ResponseContainer.getResponse();
		}

		if (response == null) {
			throw new BusinessException("传入的response为空，而且当前线程中也不存在HttpServletResponse对象");
		}
		return response;
	}

	/**
	 * 
	 * @param <T>
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getSessionAttribute(HttpServletRequest request, String key) {
		request = initRequest(request);
		return (T) request.getSession().getAttribute(key);
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @param key
	 * @param value
	 */
	public static void setSessionAttribute(HttpServletRequest request, String key, Object value) {
		request = initRequest(request);
		request.getSession().setAttribute(key, value);
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @return
	 */
	public static String getSessionId(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getId();
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @param key
	 */
	public static void removeSessionAttribute(HttpServletRequest request, String key) {
		request = initRequest(request);
		request.getSession().removeAttribute(key);
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 */
	public static void invalidateSession(HttpServletRequest request) {
		request = initRequest(request);
		request.getSession().invalidate();
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Enumeration getSessionAttributeNames(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getAttributeNames();
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @return
	 */
	public static long getSessionCreationTime(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getCreationTime();
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @return
	 */
	public static long getSessionLastAccessedTime(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getLastAccessedTime();
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @return
	 */
	public static boolean isSessionNew(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().isNew();
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @param value
	 */
	public static void setSessionMaxInactiveInterval(HttpServletRequest request, int value) {
		request = initRequest(request);
		request.getSession().setMaxInactiveInterval(value);
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @return
	 */
	public static int getSessionMaxInactiveInterval(HttpServletRequest request) {
		request = initRequest(request);
		return request.getSession().getMaxInactiveInterval();
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 */
	public static void saveToken(HttpServletRequest request) {
		request = initRequest(request);
		String token = UUID.randomUUID().toString();
		request.getSession().setAttribute(Constant.SESSION_SUBMIT_TOKEN, token);
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @param reset
	 * @return
	 */
	@Deprecated
	public static boolean isTokenValid(HttpServletRequest request, boolean reset) {
		request = initRequest(request);
		String token = request.getParameter("submitToken");
		return isTokenValid(request, reset, token);
	}

	/**
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @param reset
	 * @param token
	 * @return
	 */
	public static boolean isTokenValid(HttpServletRequest request, boolean reset, String token) {
		request = initRequest(request);
		String sessionToken = (String) request.getSession().getAttribute(Constant.SESSION_SUBMIT_TOKEN);
		boolean result = false;
		if (token == null || !token.equals(sessionToken)) {
			result = false;
		} else {
			result = true;
		}
		if (reset) {
			saveToken(request);
		}
		return result;
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @return
	 */
	public static String getClientIp(HttpServletRequest request) {
		request = initRequest(request);
		String ipAddress = request.getRemoteAddr();
		ipAddress = request.getHeader("X-Forwarded-For");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
		}

		// 对于通过多个代理的情况，第一个IP非unknown为客户端真实IP,多个IP按照','分割
		while (ipAddress != null && ipAddress.indexOf(",") > 0) {
			String addr = ipAddress.substring(0, ipAddress.indexOf(","));
			if (addr == null || addr.length() == 0 || "unknown".equalsIgnoreCase(addr)) {
				ipAddress = ipAddress.substring(ipAddress.indexOf(",") + 1);
			} else {
				ipAddress = addr;
				break;
			}

		}
		return ipAddress;
	}

	/**
	 * 
	 * @param request
	 *            传入的HttpServletRequest 可以为空
	 * @param certCode
	 *            参数中的certCode
	 * @return
	 */
	public static boolean isCertCodeValid(HttpServletRequest request, String certCode) {
		String certCodeInSession = getSessionAttribute(request, Constant.SESSION_CERT_CODE);
		return (certCode != null && certCode.equalsIgnoreCase(certCodeInSession));
	}

}
